#!/bin/bash
# Check to see if we can shut down. Return zero if can and 1 if not.
# Also perform some shut down tasks.
# Turn off cable box
# Run daily channel scan at 7 AM to fix any frequency changes done overnight 
# by Comcast.
# Run FULL mythfilldatabase once a week on Saturday, because some 
# shows for the following week may have updates.

. /etc/opt/mythtv/mythtv.conf
scriptname=`readlink -e "$0"`
scriptpath=`dirname "$scriptname"`

# Get a date/time stamp to add to log output
DATE=`date +%F\ %T\.%N`
DATE=${DATE:0:23}
today=`date "+%a %Y/%m/%d"`

# power off cable box
$scriptpath/stb_poweroff.sh

#if [[ -f /var/mythtv/checklogin ]] ; then
#    rm -f /var/mythtv/checklogin
#    echo $DATE Something going on recently - give another 5 minutes
#    exit 1
#fi

# check for channelscan run
if [[ -f /var/mythtv/channelscan_date ]]; then
    prev_channelscan=`cat /var/mythtv/channelscan_date`
fi

now=`date +%H:%M:%S`
if [[ "$now" > "$WAKEUPTIME" || "$now" == "$WAKEUPTIME" ]] ; then
    if [[ "$prev_channelscan" != "$today" ]] ; then
        $scriptpath/channelscan.sh >> /var/log/mythtv/channelscan.log 2>&1 &
        echo $DATE Starting channelscan, don\'t shut down for 10 min.
        echo $DATE > /var/mythtv/checklogin
        echo $today > /var/mythtv/channelscan_date
        exit 1
    fi
fi

# Check if mythfilldatabase is running
if ps -e|grep mythfilldatabas ; then
    echo $DATE mythfilldatabase is running, don\'t shut down for 5 min.
    exit 1
fi

# Weekly mythfilldatabase refresh-all on Saturday
if [[ "$today" == Sat* ]]; then
    if [[ -f /var/mythtv/mythrefresh_date ]] ; then
        prev_mythrefresh=`cat /var/mythtv/mythrefresh_date`
    fi
    if [[ "$prev_mythrefresh" != "$today" ]] ; then
        mythfilldatabase --refresh-all &
        echo $DATE Starting Saturday mythfilldatabase refresh-all, don\'t shut down for 10 min.
        echo $DATE > /var/mythtv/checklogin
        echo $today > /var/mythtv/mythrefresh_date
        exit 1
    fi
fi

# The leading space is important!
# if w | grep " 0 users"
if ! w | grep "^peter "
  then
#    echo $DATE peter is not logged in, ok to shut down.
    rc=0
    mythshutdown -s || rc=$?
    if [[ $rc = 16 ]] ; then
#        echo "$DATE peter logged out - OK to shut down"
        mythshutdown -u
        exit 1
    fi
    # setup defaults in database for next time
    # $scriptpath/mythstartup.sh || echo mythstartup.sh failed
  else
    echo $DATE peter is still logged in, don\'t shut down! 
#    echo $DATE > /var/mythtv/checklogin
    mythshutdown -l
    exit 1
fi

# See if flash drive to prevent shutdown is mounted
if sudo test -f /media/8841/hold_mythtv.txt
then
    echo "Drive 8841 mounted - don't shut down"
    mythshutdown -l
    exit 1
else
    rc=0
    mythshutdown -s || rc=$?
    if [[ $rc = 16 ]] ; then
#        echo "Drive 8841 removed - OK to shut down"
        mythshutdown -u
        exit 1
    fi
fi

# OK to shut down
exit 0